﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using DevExpress.XtraPrinting;
using ClinicManagement.Print;
using GeneralLibs;
using ReportGenerators._1Clinic;
using CustomSecurity;
using System.Collections;

namespace ReportGenerators.CongNo
{
    public partial class FrmThongKeLuotKham : BasicForms.FrmSupportPrintableComponents
    {
        public FrmThongKeLuotKham()
        {
            InitializeComponent();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            try
            {
                //switch (keyData)
                //{
                //    case Keys.Delete:
                //        DeleteRow();
                //        break;
                //}
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private DataTable _GridDataSouce
        {
            get
            {
                if (gridControl.DataSource is DataTable)
                    return gridControl.DataSource as DataTable;
                else if (gridControl.DataSource is DataView)
                    return (gridControl.DataSource as DataView).ToTable();
                else
                    return null;
            }
        }

        public void InitGridColumnsForPhieuDangKiKham()
        {
            gridControl.DataSource = null;
            gridView.Columns.Clear();

            int visibleIndex = 0;

            DevExpress.XtraGrid.Columns.GridColumn colMa = new DevExpress.XtraGrid.Columns.GridColumn();
            colMa.Caption = "Mã";
            colMa.FieldName = "Ma";
            colMa.Name = "colMa";
            colMa.Visible = true;
            colMa.Width = 70;
            colMa.VisibleIndex = visibleIndex++;
            colMa.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
            colMa.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;
            colMa.SummaryItem.DisplayFormat = "Tổng số = {0:### ### ### ###}";
            colMa.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;

            DevExpress.XtraGrid.Columns.GridColumn colTenLoaiPhieu = new DevExpress.XtraGrid.Columns.GridColumn();
            colTenLoaiPhieu.Caption = "Loại phiếu";
            colTenLoaiPhieu.FieldName = "TenLoaiPhieu";
            colTenLoaiPhieu.Name = "colTenLoaiPhieu";
            colTenLoaiPhieu.Visible = true;
            colTenLoaiPhieu.Width = 60;
            colTenLoaiPhieu.VisibleIndex = visibleIndex++;
            colTenLoaiPhieu.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colNgay = new DevExpress.XtraGrid.Columns.GridColumn();
            colNgay.Caption = "Ngày đăng kí";
            colNgay.FieldName = "Ngay";
            colNgay.Name = "colNgay";
            colNgay.Visible = true;
            colNgay.Width = 40;
            colNgay.VisibleIndex = visibleIndex++;
            colNgay.SortOrder = DevExpress.Data.ColumnSortOrder.Descending;
            colNgay.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;
            colNgay.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;

            DevExpress.XtraEditors.Controls.LookUpColumnInfo benhNhanInfo = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Ten", "Tên", 20);
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repLookupBenhNhan = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            repLookupBenhNhan.Columns.Add(benhNhanInfo);
            repLookupBenhNhan.ValueMember = "ID";
            repLookupBenhNhan.DisplayMember = "Ten";
            repLookupBenhNhan.DataSource = DanhMucBenhNhan.Instance.DataView;

            DevExpress.XtraGrid.Columns.GridColumn colBenhNhan = new DevExpress.XtraGrid.Columns.GridColumn();
            colBenhNhan.Caption = "Bệnh nhân";
            colBenhNhan.FieldName = "BenhNhanID";
            colBenhNhan.Name = "colBenhNhan";
            colBenhNhan.ColumnEdit = repLookupBenhNhan;
            colBenhNhan.Visible = true;
            colBenhNhan.Width = 70;
            colBenhNhan.VisibleIndex = visibleIndex++;
            colBenhNhan.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;
            colBenhNhan.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;

            DevExpress.XtraGrid.Columns.GridColumn colTenCoQuan = new DevExpress.XtraGrid.Columns.GridColumn();
            colTenCoQuan.Caption = "Tên cơ quan";
            colTenCoQuan.FieldName = "TenCoQuan";
            colTenCoQuan.Name = "colTenCoQuan";
            colTenCoQuan.Visible = true;
            colTenCoQuan.Width = 80;
            colTenCoQuan.VisibleIndex = visibleIndex++;
            colTenCoQuan.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraEditors.Controls.LookUpColumnInfo DichVuInfo = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Ten", "Tên", 20);
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repLookupDichVu = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            repLookupDichVu.Columns.Add(DichVuInfo);
            repLookupDichVu.ValueMember = "ID";
            repLookupDichVu.DisplayMember = "Ten";
            repLookupDichVu.DataSource = DanhMucDichVu.Instance.DataView;

            DevExpress.XtraGrid.Columns.GridColumn colDichVu = new DevExpress.XtraGrid.Columns.GridColumn();
            colDichVu.Caption = "Dịch vụ";
            colDichVu.FieldName = "DichVuID";
            colDichVu.Name = "colDichVu";
            colDichVu.ColumnEdit = repLookupDichVu;
            colDichVu.Visible = true;
            colDichVu.Width = 80;
            colDichVu.VisibleIndex = visibleIndex++;
            colDichVu.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraEditors.Controls.LookUpColumnInfo bacSiInfo = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("FullName", "Tên", 20);
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repLookupBacSi = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            repLookupBacSi.Columns.Add(bacSiInfo);
            repLookupBacSi.ValueMember = "ID";
            repLookupBacSi.DisplayMember = "FullName";
            repLookupBacSi.DataSource = UserList.Instance.DataTable.DefaultView;

            DevExpress.XtraGrid.Columns.GridColumn colBacSi = new DevExpress.XtraGrid.Columns.GridColumn();
            colBacSi.Caption = "Bác sĩ";
            colBacSi.FieldName = "BacSiID";
            colBacSi.Name = "colBacSi";
            colBacSi.ColumnEdit = repLookupBacSi;
            colBacSi.Visible = true;
            colBacSi.VisibleIndex = visibleIndex++;
            colBacSi.Width = 70;
            colBacSi.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraEditors.Controls.LookUpColumnInfo ThuNganInfo = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("FullName", "Tên", 20);
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repLookupThuNgan = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            repLookupThuNgan.Columns.Add(ThuNganInfo);
            repLookupThuNgan.ValueMember = "ID";
            repLookupThuNgan.DisplayMember = "FullName";
            repLookupThuNgan.DataSource = UserList.Instance.DataTable.DefaultView;

            //Thu ngân là UserID chứ k phải người tạo phiếu, vì y tá chỉ định k thu tiền
            DevExpress.XtraGrid.Columns.GridColumn colThuNgan = new DevExpress.XtraGrid.Columns.GridColumn();
            colThuNgan.Caption = "Thu ngân";
            colThuNgan.FieldName = "UserID";
            colThuNgan.Name = "colThuNgan";
            colThuNgan.ColumnEdit = repLookupThuNgan;
            colThuNgan.Visible = true;
            colThuNgan.VisibleIndex = visibleIndex++;
            colThuNgan.Width = 70;
            colThuNgan.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colSoPhieuThu = new DevExpress.XtraGrid.Columns.GridColumn();
            colSoPhieuThu.Caption = "Số phiếu thu";
            colSoPhieuThu.FieldName = "SoPhieuThu";
            colSoPhieuThu.Name = "colSoPhieuThu";
            colSoPhieuThu.Visible = true;
            colSoPhieuThu.Width = 80;
            colSoPhieuThu.VisibleIndex = visibleIndex++;
            colSoPhieuThu.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraEditors.Controls.LookUpColumnInfo PhongBanInfo = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Ten", "Tên", 20);
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repLookupPhongBan = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            repLookupPhongBan.Columns.Add(PhongBanInfo);
            repLookupPhongBan.ValueMember = "ID";
            repLookupPhongBan.DisplayMember = "Ten";
            repLookupPhongBan.DataSource = DanhMucDoiTuongNghiepVu.Instance.DataView;

            DevExpress.XtraGrid.Columns.GridColumn colPhongBan = new DevExpress.XtraGrid.Columns.GridColumn();
            colPhongBan.Caption = "Phòng chuyên môn";
            colPhongBan.FieldName = "PhongBanID";
            colPhongBan.Name = "colPhongBan";
            colPhongBan.ColumnEdit = repLookupPhongBan;
            colPhongBan.Visible = true;
            colPhongBan.VisibleIndex = visibleIndex++;
            colPhongBan.Width = 80;
            colPhongBan.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colTinhTrangBenh = new DevExpress.XtraGrid.Columns.GridColumn();
            colTinhTrangBenh.Caption = "Tình trạng bệnh khi đi khám";
            colTinhTrangBenh.FieldName = "TinhTrangBenh";
            colTinhTrangBenh.Name = "colTinhTrangBenh";
            colTinhTrangBenh.Visible = true;
            colTinhTrangBenh.Width = 60;
            colTinhTrangBenh.VisibleIndex = visibleIndex++;
            colTinhTrangBenh.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colSTTKham = new DevExpress.XtraGrid.Columns.GridColumn();
            colSTTKham.Caption = "STT khám";
            colSTTKham.FieldName = "SoThuTuKham";
            colSTTKham.Name = "colSTTKham";
            colSTTKham.Visible = true;
            colSTTKham.Width = 30;
            colSTTKham.VisibleIndex = visibleIndex++;
            colSTTKham.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colTaiKham = new DevExpress.XtraGrid.Columns.GridColumn();
            colTaiKham.Caption = "Tái khám";
            colTaiKham.FieldName = "TaiKham";
            colTaiKham.Name = "colTaiKham";
            colTaiKham.Visible = true;
            colTaiKham.Width = 30;
            colTaiKham.VisibleIndex = visibleIndex++;
            colTaiKham.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colSoTheBHYT = new DevExpress.XtraGrid.Columns.GridColumn();
            colSoTheBHYT.Caption = "Có BHYT";
            colSoTheBHYT.FieldName = "SoTheBHYT";
            colSoTheBHYT.Name = "colSoTheBHYT";
            colSoTheBHYT.Visible = true;
            colSoTheBHYT.Width = 30;
            colSoTheBHYT.VisibleIndex = visibleIndex++;
            colSoTheBHYT.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colTienThanhToan = new DevExpress.XtraGrid.Columns.GridColumn();
            colTienThanhToan.Caption = "Tiền T.toán";
            colTienThanhToan.FieldName = "TienThanhToan";
            colTienThanhToan.Name = "colTienThanhToan";
            colTienThanhToan.Visible = true;
            colTienThanhToan.Width = 50;
            colTienThanhToan.VisibleIndex = visibleIndex++;
            colTienThanhToan.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;
            colTienThanhToan.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
            colTienThanhToan.SummaryItem.DisplayFormat = "{0:### ### ### ###}";

            DevExpress.XtraGrid.Columns.GridColumn colGhiChu = new DevExpress.XtraGrid.Columns.GridColumn();
            colGhiChu.Caption = "Ghi chú";
            colGhiChu.FieldName = "GhiChu";
            colGhiChu.Name = "colGhiChu";
            colGhiChu.Visible = true;
            colGhiChu.Width = 60;
            colGhiChu.VisibleIndex = visibleIndex++;
            colGhiChu.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colDaThuTien = new DevExpress.XtraGrid.Columns.GridColumn();
            colDaThuTien.Caption = "Đã thu tiền";
            colDaThuTien.FieldName = "DaThuTien";
            colDaThuTien.Name = "colDaThuTien";
            colDaThuTien.Visible = true;
            colDaThuTien.Width = 30;
            colDaThuTien.VisibleIndex = visibleIndex++;
            colDaThuTien.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colDaXuLy = new DevExpress.XtraGrid.Columns.GridColumn();
            colDaXuLy.Caption = "Đã xử lý";
            colDaXuLy.FieldName = "DaXuLy";
            colDaXuLy.Name = "colDaXuLy";
            colDaXuLy.Visible = true;
            colDaXuLy.Width = 30;
            colDaXuLy.VisibleIndex = visibleIndex++;
            colDaXuLy.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            this.gridView.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] {
                colMa, colNgay, colTenLoaiPhieu, colBenhNhan, colTenCoQuan, colDichVu, colBacSi, colPhongBan, colThuNgan, colTinhTrangBenh,
                colTaiKham, colSoTheBHYT, colTienThanhToan, colGhiChu, colDaThuTien, colDaXuLy });

            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
                column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            }
        }

        private void FrmThongKeLuotKham_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                cmbKyBaoCao.SelectedText = "Hôm nay";

                #region cmbBacSy
                string maNhom = "BacSi";
                cmbBacSi.DataSource = UserList.Instance.GetDanhSachNguoiDungByMaNhom(maNhom).DefaultView;
                cmbBacSi.DisplayColumn = "FullName";
                cmbBacSi.ValueColumn = "ID";
                cmbBacSi.AddVisibleColumn("FullName", "Tên bác sĩ");
                #endregion

                #region cmbThuNgan
                maNhom = "ThuNgan";
                //cmbThuNgan.DataSource = UserList.Instance.GetDanhSachNguoiDungByMaNhom(maNhom).DefaultView;
                cmbThuNgan.DataSource = UserList.Instance.DataTable.DefaultView;
                cmbThuNgan.DisplayColumn = "FullName";
                cmbThuNgan.ValueColumn = "ID";
                cmbThuNgan.AddVisibleColumn("FullName", "Tên thu ngân");
                #endregion

                #region cmbPhongBan
                cmbPhongBan.DataSource = DanhMucDoiTuongNghiepVu.GetDanhMucPhongBan().DataView;
                cmbPhongBan.DisplayColumn = "Ten";
                cmbPhongBan.ValueColumn = "ID";
                cmbPhongBan.AddVisibleColumn("Ma", "Mã", 100, 1);
                cmbPhongBan.AddVisibleColumn("Ten", "Tên", 320, 2);
                #endregion

                #region cmbCoQuan
                cmbCoQuan.DataSource = DanhMucCoQuan.Instance.DataView;
                cmbCoQuan.DisplayColumn = "Ten";
                cmbCoQuan.ValueColumn = "ID";
                cmbCoQuan.AddVisibleColumn("Ma", "Mã", 100, 1);
                cmbCoQuan.AddVisibleColumn("Ten", "Tên", 320, 2);
                #endregion

                InitGridColumnsForPhieuDangKiKham();

                foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
                {
                    column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
                    column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
                }

                FormatGridViewForCopyCell(gridView); //KCB thì cho copy trong các report
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
        private void cmbBacSi_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbBacSi.EditValue = Guid.Empty;
        }
        private void cmbPhongBan_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbPhongBan.EditValue = Guid.Empty;
        }
        private void cmbThuNgan_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbThuNgan.EditValue = Guid.Empty;
        }
        private void cmbCoQuan_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbCoQuan.EditValue = Guid.Empty;
        }

        private void gridView_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            DateTime ngayBatDau = new DateTime(); if (LocalSettings.HeThong.CheDoBiKiemTra) ngayBatDau = DateTime.Now.AddDays(-2); else ngayBatDau = dtNgayBatDau.DateTime; //DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if (!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;
            string kyBaoCao = cmbKyBaoCao.Text;
            if (kyBaoCao == "Cả năm") kyBaoCao = "Năm " + GeneralLibs.Config.NamTaiChinh.ToString();
            else if (kyBaoCao == "Tùy chọn") kyBaoCao = string.Format("Từ ngày {0}/{1}/{2} đến ngày {3}/{4}/{5}",
                                       ngayBatDau.Day, ngayBatDau.Month, ngayBatDau.Year,
                                       ngayKetThuc.Day, ngayKetThuc.Month, ngayKetThuc.Year);

            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandTimeout = GeneralLibs.Config.TimeOut;

                //Các điều kiện tìm kiếm
                string BHYTCondition = "1 = 1";
                string bacSiCondition = "1 = 1";
                string thuNganCondition = "1 = 1";
                string phongBanCondition = "1 = 1";
                string coQuanCondition = "1 = 1";

                //string maLoaiPhieu = "PĐK";    //Phiếu đăng kí
                //LoaiPhieu loaiPhieu = DanhMucLoaiPhieu.Instance.GetByMa(maLoaiPhieu);

                if (cmbBacSi.EditValue != null && (Guid)cmbBacSi.EditValue != Guid.Empty)
                    bacSiCondition = string.Format("BacSiID = '{0}'", cmbBacSi.EditValue);
                //Lấy qua bảng ChungTu nên phải so UserID chứ k phải ThuNhanID
                if (cmbThuNgan.EditValue != null && (Guid)cmbThuNgan.EditValue != Guid.Empty)
                    thuNganCondition = string.Format("UserID = '{0}'", cmbThuNgan.EditValue);
                if (cmbPhongBan.EditValue != null && (Guid)cmbPhongBan.EditValue != Guid.Empty)
                    phongBanCondition = string.Format("PhongBanID = '{0}'", cmbPhongBan.EditValue);
                if (cmbCoQuan.EditValue != null && (Guid)cmbCoQuan.EditValue != Guid.Empty)
                    coQuanCondition = string.Format("CoQuanBenhNhanID = '{0}'", cmbCoQuan.EditValue);

                if (chkCoBHYT.Checked && !chkKhongBHYT.Checked) //lấy có thẻ BHYT
                    BHYTCondition = string.Format("SoTheBHYT <> ''");
                else if (!chkCoBHYT.Checked && chkKhongBHYT.Checked) //lấy không có thẻ BHYT
                    BHYTCondition = string.Format("(SoTheBHYT = '' OR SoTheBHYT IS NULL)");
                else if (!chkCoBHYT.Checked && !chkKhongBHYT.Checked) //k tích cả 2 --> không lấy gì
                    BHYTCondition = "1 = 0";

                cmd.CommandText = string.Format("SELECT * FROM ( \n" +
                                                "--Chi tiết dịch vụ theo phiếu đăng kí, 1 phiếu đăng kí chỉ có 1 dịch vụ \n" +
                                                "SELECT D.So SoPhieuThu, D.UserID, E.FullName,   \n" +
                                                "   A.Ma, A.Ngay, A.BenhNhanID, A.BacSiID, A.PhongBanID, A.TinhTrangBenh, A.SoThuTuKham, A.TaiKham,  \n" +
                                                "   A.SoTheBHYT, A.TienThanhToan, A.GhiChu, A.DaThuTien, A.DaXuLy, \n" +
                                                "   A.DichVuID,B. Ten TenBenhNhan, C.Ten DienGiai, LP.Ten TenLoaiPhieu, \n" +
                                                "   CQ.ID CoQuanBenhNhanID, CQ.Ten TenCoQuan \n" +
                                                "FROM Clinic_Phieu A INNER JOIN Clinic_LoaiPhieu LP ON A.LoaiPhieuID = LP.ID AND LP.Ma = N'PĐK' \n" +
                                                "	INNER JOIN Clinic_BenhNhan B ON A.BenhNhanID = B.ID  \n" +
                                                "   LEFT JOIN Clinic_CoQuan CQ ON CQ.ID = B.CoQuanID  \n" +
                                                "	LEFT JOIN Clinic_DichVu C ON C.ID = A.DichVuID  \n" +
                                                "	LEFT JOIN ChungTu D ON A.ID = D.Clinic_PhieuID  \n" +
                                                "	LEFT JOIN [User] E ON D.UserID = E.ID  \n" +
                                                "UNION \n" +
                                                "--Chi tiết dịch vụ theo phiếu chỉ định, 1 phiếu chỉ định có nhiều dịch vụ \n" +
                                                "SELECT D.So SoPhieuThu, D.UserID, E.FullName,   \n" +
                                                "   A.Ma, A.Ngay, A.BenhNhanID, A.BacSiID, NHOMDV.PhongBanID, A.TinhTrangBenh, A.SoThuTuKham, A.TaiKham,  \n" +
                                                "   A.SoTheBHYT, KM.ThanhTien, A.GhiChu, A.DaThuTien, A.DaXuLy, \n" +
                                                "   KM.DichVuID, B. Ten TenBenhNhan, C.Ten DienGiai, LP.Ten TenLoaiPhieu, \n" +
                                                "   CQ.ID CoQuanBenhNhanID, CQ.Ten TenCoQuan \n" +
                                                "FROM Clinic_Phieu A INNER JOIN Clinic_LoaiPhieu LP ON A.LoaiPhieuID = LP.ID AND LP.Ma IN( N'PCĐBS', N'PCĐLT') \n" +
                                                "	INNER JOIN Clinic_KhoanMucPhieu KM ON A.ID = KM.PhieuID \n" +
                                                "	INNER JOIN Clinic_BenhNhan B ON A.BenhNhanID = B.ID  \n" +
                                                "   LEFT JOIN Clinic_CoQuan CQ ON CQ.ID = B.CoQuanID  \n" +
                                                "	LEFT JOIN Clinic_DichVu C ON C.ID = KM.DichVuID  \n" +
                                                "	INNER JOIN Clinic_NhomDichVu NHOMDV ON C.NhomDichVuID = NHOMDV.ID \n" +
                                                "	LEFT JOIN ChungTu D ON A.ID = D.Clinic_PhieuID  \n" +
                                                "	LEFT JOIN [User] E ON D.UserID = E.ID  \n" +
                                                ") AS TBL  \n" +
                                                "WHERE {0} AND {1} AND {2} AND {3} AND {4}\n" +
                                                "	AND @ThoiDiemDau <= Ngay AND Ngay <= @ThoiDiemCuoi \n",
                                                bacSiCondition, thuNganCondition, phongBanCondition, coQuanCondition, BHYTCondition);

                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@ThoiDiemDau", ngayBatDau);
                cmd.Parameters.AddWithValue("@ThoiDiemCuoi", ngayKetThuc);

                SqlDataAdapter da = new SqlDataAdapter(cmd);

                //Báo cáo động --> k cần tạo dataset làm gì cho mất công
                DataTable dt = new DataTable();
                da.Fill(dt);

                gridControl.DataSource = dt;

                FormatNumberInGridView(gridView);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
            }
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            try
            {
                string option1 = string.Format("Từ {0}:{1} ngày {2}/{3}/{4} đến {5}:{6} ngày {7}/{8}/{9}",
                                dtNgayBatDau.DateTime.Hour, dtNgayBatDau.DateTime.Minute,
                                dtNgayBatDau.DateTime.Day, dtNgayBatDau.DateTime.Month, dtNgayBatDau.DateTime.Year,
                                dtNgayKetThuc.DateTime.Hour, dtNgayKetThuc.DateTime.Minute,
                                dtNgayKetThuc.DateTime.Day, dtNgayKetThuc.DateTime.Month, dtNgayKetThuc.DateTime.Year);
                string option2 = "";

                gridView.OptionsPrint.MaxMergedCellHeight = -1;  //Để in ra cũng merge cell y như gridcontrol
                PrintWithHeaderAndFooter(true, gridControl, true, true, "THỐNG KÊ LƯỢT KHÁM CHỮA BỆNH", option1, option2, "", "");
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                //PrintClinic print = new PrintClinic();
                //if (_GridDataSouce != null)
                //    print.PrintBangKeThue(_GridDataSouce);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
      
        //Event cho cả 3 radio luôn. Cụ thể thì sẽ xử lý bên trong
        private void rdoGroup_CheckedChanged(object sender, EventArgs e)
        {
            NhomTheoTieuChi();
        }
        private void btnBoNhom_Click(object sender, EventArgs e)
        {
            rdoGroupBacSi.Checked = false;
            rdoGroupByThuNgan.Checked = false;
            rdoGroupPhongBan.Checked = false;
        }
        private void NhomTheoTieuChi()
        {
            try
            {
                //Ban đầu vào re group hết đi rồi group lại
                gridView.OptionsView.ShowGroupPanel = false;
                gridView.OptionsCustomization.AllowGroup = false;
                gridView.OptionsBehavior.AutoExpandAllGroups = false;

                gridView.Columns["BacSiID"].SortOrder = DevExpress.Data.ColumnSortOrder.None;
                gridView.Columns["BacSiID"].OptionsColumn.AllowGroup = DevExpress.Utils.DefaultBoolean.False;
                gridView.Columns["BacSiID"].UnGroup();

                gridView.Columns["UserID"].SortOrder = DevExpress.Data.ColumnSortOrder.None;
                gridView.Columns["UserID"].OptionsColumn.AllowGroup = DevExpress.Utils.DefaultBoolean.False;
                gridView.Columns["UserID"].UnGroup();

                gridView.Columns["PhongBanID"].SortOrder = DevExpress.Data.ColumnSortOrder.None;
                gridView.Columns["PhongBanID"].OptionsColumn.AllowGroup = DevExpress.Utils.DefaultBoolean.False;
                gridView.Columns["PhongBanID"].UnGroup();

                gridView.GroupSummary.Clear();
                gridView.GroupFooterShowMode = DevExpress.XtraGrid.Views.Grid.GroupFooterShowMode.Hidden;

                //Group lại theo tiêu chí
                if (rdoGroupBacSi.Checked)
                {
                    //code để group theo nhóm
                    gridView.OptionsView.ShowGroupPanel = true;
                    gridView.OptionsCustomization.AllowGroup = true;
                    gridView.OptionsBehavior.AutoExpandAllGroups = false;
                    gridView.Columns["BacSiID"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
                    gridView.Columns["BacSiID"].OptionsColumn.AllowGroup = DevExpress.Utils.DefaultBoolean.True;
                    gridView.Columns["BacSiID"].Group();

                    gridView.GroupSummary.Clear();
                    gridView.GroupFooterShowMode = DevExpress.XtraGrid.Views.Grid.GroupFooterShowMode.VisibleIfExpanded;

                    // Hiện tổng tiền theo nhóm
                    DevExpress.XtraGrid.GridGroupSummaryItem item = new DevExpress.XtraGrid.GridGroupSummaryItem();
                    item.FieldName = "TienThanhToan";
                    item.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                    item.DisplayFormat = " (Tổng tiền = {0:### ### ### ###})";
                    item.Tag = "TienThanhToan";
                    gridView.GroupSummary.Add(item);
                }
                else if (rdoGroupByThuNgan.Checked)
                {
                    //code để group theo nhóm
                    gridView.OptionsView.ShowGroupPanel = true;
                    gridView.OptionsCustomization.AllowGroup = true;
                    gridView.OptionsBehavior.AutoExpandAllGroups = false;
                    gridView.Columns["UserID"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
                    gridView.Columns["UserID"].OptionsColumn.AllowGroup = DevExpress.Utils.DefaultBoolean.True;
                    gridView.Columns["UserID"].Group();

                    gridView.GroupSummary.Clear();
                    gridView.GroupFooterShowMode = DevExpress.XtraGrid.Views.Grid.GroupFooterShowMode.VisibleIfExpanded;

                    // Hiện tổng tiền theo nhóm
                    DevExpress.XtraGrid.GridGroupSummaryItem item = new DevExpress.XtraGrid.GridGroupSummaryItem();
                    item.FieldName = "TienThanhToan";
                    item.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                    item.DisplayFormat = " (Tổng tiền = {0:### ### ### ###})";
                    item.Tag = "TienThanhToan";
                    gridView.GroupSummary.Add(item);
                }
                else if (rdoGroupPhongBan.Checked)
                {
                    gridView.OptionsView.ShowGroupPanel = true;
                    gridView.OptionsCustomization.AllowGroup = true;
                    gridView.OptionsBehavior.AutoExpandAllGroups = false;
                    gridView.Columns["PhongBanID"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
                    gridView.Columns["PhongBanID"].OptionsColumn.AllowGroup = DevExpress.Utils.DefaultBoolean.True;
                    gridView.Columns["PhongBanID"].Group();

                    gridView.GroupSummary.Clear();
                    gridView.GroupFooterShowMode = DevExpress.XtraGrid.Views.Grid.GroupFooterShowMode.VisibleIfExpanded;

                    // Hiện tổng tiền theo nhóm
                    DevExpress.XtraGrid.GridGroupSummaryItem item = new DevExpress.XtraGrid.GridGroupSummaryItem();
                    item.FieldName = "TienThanhToan";
                    item.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                    item.DisplayFormat = " (Tổng tiền = {0:### ### ### ###})";
                    item.Tag = "TienThanhToan";
                    gridView.GroupSummary.Add(item);
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
    }
}
